package com.hundsun.fcp.webplugin.fragments;

import java.util.Stack;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;

import com.alibaba.fastjson.JSON;
import com.hundsun.fcp.base.BaseFragment;
import com.hundsun.fcp.common.WebUrlConfig;
import com.hundsun.fcp.common.logger.AndroidLogger;
import com.hundsun.fcp.common.logger.Logger;
import com.hundsun.fcp.impl.IFooterMenuHiddenListener;
import com.hundsun.fcp.webplugin.FundTradingFunction;
import com.hundsun.fcp.webplugin.FundTradingHelper;
import com.hundsun.fcp.webplugin.WebPluginConfig;
import com.hundsun.fcp.webplugin.WebPluginVerification;
import com.hundsun.fcp.webplugin.WebPluginVerification.ICheckUpdateListener;
import com.hundsun.fcp.webplugin.bean.TradeParamBase;
import com.hundsun.fcp.webplugin.bean.UpdateManifestBean;
import com.hundsun.fcp.webplugin.service.update.IUpdateListener;
import com.hundsun.fcp.webplugin.util.NetWorkUtil;
import com.hundsun.fcp.webplugin.util.SdCardUtil;
import com.hundsun.fcp.webplugin.widget.webview.FcpWebChromeClient;
import com.hundsun.fcp.webplugin.widget.webview.FcpWebView;
import com.hundsun.fcp.webplugin.widget.webview.FcpWebView.IWebViewDelegator;
import com.hundsun.fcp.webplugin.widget.webview.FcpWebViewClient;
import com.hundsun.fcp.webplugin.widget.webview.FcpWebViewClient.IWebViewClientEvtHandler;

public abstract class FcpFundTradingFragment extends Fragment implements KeyEvent.Callback,IWebViewClientEvtHandler,IUpdateListener{
	private static final Logger LOGGER = AndroidLogger.getLogger() ;
	private String dialogTitle = "基金交易";
	private FrameLayout mContentView;
	private Stack<FcpWebView> mWebViewContainer;
	private Activity mActivity ;
	private FcpWebView mWebView ;
	private FcpWebViewClient mWebViewClient;
	private FcpWebChromeClient mWebChromeClient ;
	private Animation mAnimationPageEnter;
	private Animation mAnimationPageLeave;
	private View mLoadingView ;
	/**是否需要更新*/
	private AtomicBoolean needUpdated = new AtomicBoolean(false);
	/**是否已加载*/
	private AtomicBoolean mLoaded = new AtomicBoolean(false) ;
	
	private Handler mHandler = new Handler();
	private AtomicReference<String> mLastOverrideUrl = new AtomicReference<String>("");
	
	private ProgressDialog mProgressDialog ;
	
	private IFooterMenuHiddenListener mHiddenListener ;
	
	private long mTradeActionDelayed = 0 ;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mWebViewContainer = new Stack();
		mWebViewClient = new FcpWebViewClient(mActivity) ;
		mWebViewClient.setWebViewEvtHandler(this) ;
		mWebChromeClient = new FcpWebChromeClient();
		mLoadingView = getLoadingView() ;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		if(mContentView==null){
			mContentView = new FrameLayout(mActivity);
			 FrameLayout.LayoutParams _LayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
			 mContentView.setLayoutParams(_LayoutParams);
		}
		
		return mContentView;
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		if(mContentView!=null){
			((ViewGroup)mContentView.getParent()).removeView(mContentView) ;
		}
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if(mLoadingView!=null){
			mContentView.addView(mLoadingView);
		}
		mWebView = createAndInitiateWebView();
		
		if(!NetWorkUtil.isConnected(mActivity)){
			showAlertDialog("无法连接服务器，请检查网络连接");
			LOGGER.debug("无法连接服务器，请检查网络连接");
			return;
		}
		
		if (!SdCardUtil.existBaseDir(getActivity()))
	    {
	      showAlertDialog("未检测到SD卡，请检查设置");
	      LOGGER.debug("未检测到SD卡，请检查设置");
	      return;
	    }
		
		if(!mLoaded.get()){
			doAction(mTradeActionDelayed) ;
			mLoaded.set(true) ;
		}
		
		//TODO...插件检测更新
		/*final WebPluginVerification pluginVerification = WebPluginVerification.getInstance(mActivity) ;
		pluginVerification.setCheckUpdateListener(new ICheckUpdateListener() {
			
			@Override
			public void onCheckNeedUpdate(UpdateManifestBean pUpdateManifestBean) {
				checkNeedUpdateDialog(pluginVerification, pUpdateManifestBean);
			}

			
			@Override
			public void onCheckFailed(final String errorMsg, Throwable errorThrowable) {
				mHandler.post(new Runnable()
		        {
		          public void run()
		          {
		            if (canContinue()) {
		              showAlertDialog(errorMsg);
		            }
		          }
		        });
			}
			
			@Override
			public void onCheckDone() {
				doAction(mTradeActionDelayed) ;
			}
		}) ;
		pluginVerification.checkPluginNeedUpdate() ;*/
		
	}
	
	private FcpWebView createAndInitiateWebView() {
		FcpWebView fcpWebView = new FcpWebView(this.mActivity);
		fcpWebView.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
		fcpWebView.initWebViewInfo();
		fcpWebView.setWebViewDelegator(new IWebViewDelegator() {

			@Override
			public void quitSdk(FcpWebView pFcpWebView) {
				FcpFundTradingFragment.this.quitSdk();
			}

			@Override
			public void goBack(FcpWebView pFcpWebView) {
				pFcpWebView.clearLocalStorage();
				showPageLeaveAnim(pFcpWebView);
				mContentView.removeView(pFcpWebView);
				mWebViewContainer.remove(pFcpWebView);
				if(mWebViewContainer.size()<=1){
		        	  if(mHiddenListener!=null){
		        		  mHiddenListener.visiable() ;
		        	  }
		          }
			}

			@Override
			public boolean canGoBack(FcpWebView pFcpWebView) {
				return mWebViewContainer.size() > 1;
			}
		});
		fcpWebView.setWebViewClient(mWebViewClient);
		fcpWebView.setWebChromeClient(mWebChromeClient);
		return fcpWebView;
	}
	
	protected void showPageLeaveAnim(View pView)
	{
	    if (this.mAnimationPageLeave != null)
	    {
	      this.mAnimationPageLeave.setStartOffset(0L);
	      pView.startAnimation(this.mAnimationPageLeave);
	    }
	}
	
	 protected void showPageEnterAnim(View paramView)
	 {
	    if (this.mAnimationPageEnter != null)
	    {
	      this.mAnimationPageEnter.setStartOffset(0L);
	      paramView.startAnimation(this.mAnimationPageEnter);
	    }
	 }
	
	public void setPageAnimation(Animation pAnimationPageEnter, Animation pAnimationPageLeave)
	{
		this.mAnimationPageEnter = pAnimationPageEnter;
		this.mAnimationPageLeave = pAnimationPageLeave;
	}

	protected View getLoadingView()
	{
	    return null;
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		this.mActivity = activity ;
	}
	
	public void showAlertDialog(String pMessage) {
		if (TextUtils.isEmpty(pMessage)) {
			return;
		}
		AlertDialog.Builder _Builder = new AlertDialog.Builder(getActivity());
		if (!TextUtils.isEmpty(getDialogTitle())) {
			_Builder.setTitle(getDialogTitle());
		}
		_Builder.setMessage(pMessage);
		_Builder.setCancelable(false);
		_Builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface pDialogInterface, int pInt) {
				pDialogInterface.dismiss();
				quitSdk();
			}
		});
		AlertDialog _AlertDialog = _Builder.create();
		_AlertDialog.setCanceledOnTouchOutside(false);
		_AlertDialog.show();
	}
	
	protected final void doAction(long delayMillis)
	{
		this.mHandler.postDelayed(new Runnable()
	    {
	      public void run()
	      {
	        FcpFundTradingFragment.this.doFundTrading();
	      }
	    }, delayMillis);
	}
	
	private void doFundTrading() {
		Bundle _Bundle = getArguments();
		FundTradingFunction _Function = FundTradingHelper.getTradingFunction(_Bundle);
		TradeParamBase _ParamBase = FundTradingHelper.getTradingParam(_Bundle) ;
		if(_ParamBase!=null){
			mWebView.setTag(JSON.toJSONString(_ParamBase)) ;
		}
		
		if (!this.mWebViewContainer.contains(mWebView)) {
			this.mContentView.addView(mWebView);
			this.mWebViewContainer.add(mWebView);
			if (this.needUpdated.getAndSet(false)) {
				showPageEnterAnim(mWebView);
			}
		}
		this.mWebView.loadPluginPage(_Function);
	}

	public void quitSdk() {
		if (this.mWebView != null) {
			this.mWebView.clearLocalStorage();
		}
		doQuitSdk();
	}

	public abstract void doQuitSdk();

	private CharSequence getDialogTitle() {
		return dialogTitle;
	}
	
	protected void showCustomProgressDialog(Context pContext, String pMsg) {
		this.mProgressDialog = ProgressDialog.show(pContext, getDialogTitle(),
				pMsg);
	}

	private void setProgressDialogText(String paramString) {
		try {
			this.mProgressDialog.setMessage(paramString);
		} catch (Exception e) {
			LOGGER.error(e.getMessage() + "", e);
		}
	}

	private void showProgressDialog() {
		try {
			showCustomProgressDialog(this.mActivity, "功能更新中，请稍候..");
		} catch (Exception e) {
			LOGGER.error(e.getMessage() + "", e);
		}
	}

	private void dismissProgressDialog(int delayMillis) {
		this.mHandler.postDelayed(new Runnable() {
			public void run() {
				try {
					dismissCustomProgressDialog();
				} catch (Exception e) {
					LOGGER.error(e.getMessage() + "", e);
				}
			}
		}, delayMillis);
	}

	protected void dismissCustomProgressDialog() {
		mProgressDialog.dismiss();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		return false;
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		return false;
	}

	@Override
	public boolean onKeyMultiple(int keyCode, int count, KeyEvent event) {
		return false;
	}
	
	@Override
	public void onPageStarted(WebView pWebView, String url, Bitmap favicon,
			FcpWebViewClient pFcpWebViewClient) {
		if(!TextUtils.isEmpty(url)){
			if(url.startsWith(WebUrlConfig.LOAD_LOCALPAGE)&& !(mLastOverrideUrl.getAndSet("")).equals(url)){
				url = url.replace(WebUrlConfig.LOAD_LOCALPAGE, SdCardUtil.locateHtmlFilePath(mActivity));
				pWebView.stopLoading();
				if(WebPluginConfig.isSeperateWebView()){
					FcpWebView _WebView = createAndInitiateWebView();
			        this.mContentView.addView(_WebView);
			        this.mWebViewContainer.add(_WebView);
			        this.mWebView = _WebView;
			        _WebView.requestFocus();
			        showPageEnterAnim(_WebView);
			        _WebView.loadUrl(url);
				}else{
					pWebView.requestFocus() ;
					pWebView.loadUrl(url) ;
				}
			}
		}
	}
	
	@Override
	public void onPageFinished(final WebView pWebView, String url,
			FcpWebViewClient pFcpWebViewClient) {
		//function clientCall(data)
		mHandler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				String data = (String) pWebView.getTag() ;
				String pageFinishCallJs = String.format("javascript:if (typeof clientCall == 'function') { clientCall('%s'); }", data) ;
				pWebView.loadUrl(pageFinishCallJs) ;
				LOGGER.debug("clientCall加载完成");
			}
		}, 100) ;
		
	}
	
	@Override
	public boolean shouldOverrideUrlLoading(WebView pWebView, String url,
			FcpWebViewClient pFcpWebViewClient) {
		
		if (url.startsWith(WebUrlConfig.LOAD_LOCALPAGE))
	    {
	      mLastOverrideUrl.set(url);
	      url = url.replace(WebUrlConfig.LOAD_LOCALPAGE,SdCardUtil.locateHtmlFilePath(this.mActivity));
	      if (WebPluginConfig.isSeperateWebView())
	      {
	        FcpWebView _FcpWebView = createAndInitiateWebView();
	        if (!this.mWebViewContainer.contains(_FcpWebView))
	        {
	          this.mContentView.addView(_FcpWebView);
	          this.mWebViewContainer.add(_FcpWebView);
	          this.mWebView = _FcpWebView;
	          _FcpWebView.requestFocus();
	          showPageEnterAnim(_FcpWebView);
	          _FcpWebView.loadUrl(url);
	          if(mWebViewContainer.size()>1){
	        	  if(mHiddenListener!=null){
	        		  mHiddenListener.gone() ;
	        	  }
	          }
	        }
	        return true;
	      } 
	      pWebView.requestFocus();
	      pWebView.loadUrl(url);
	      return true;
	    }
	    if ((url.startsWith("tel:")) || (url.startsWith("market://")))
	    {
	      Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse(url));
	      this.mActivity.startActivity(viewIntent);
	      return true;
	    }
		return false;
	}

	@Override
	public void onUpdateDone() {
		doAction(this.mTradeActionDelayed) ;
	}

	@Override
	public void onUpdateFailed(final String pErrorMsg, Throwable error) {
		this.mHandler.post(new Runnable()
	    {
	      public void run()
	      {
	        if (canContinue()) {
	        	showAlertDialog(pErrorMsg);
	        }
	      }
	    });
	}

	@Override
	public void onUpdateFinish() {  
	    setProgressDialogText(String.format("插件下载中，请稍候 %d%%", 100));
	    dismissProgressDialog(1000);
	}

	@Override
	public void onUpdateProgress(int progressSize, int totalSize) {
		if (totalSize != 0)
	    {
	      int progress = progressSize * 100 / totalSize; 
	      setProgressDialogText(String.format("插件下载中，请稍候 %d%%", progress));
	    }
	}

	@Override
	public void onUpdateStart() {
		showProgressDialog();
	}
	
	@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
	protected boolean canContinue(){
		if(getActivity()==null){
			return false ;
		}
		if(getActivity()!=null){
			if(getActivity().isFinishing()||(Build.VERSION.SDK_INT>=17&&getActivity().isDestroyed())){
				return false ;
			}
		}
		return true ;
	}

	public IFooterMenuHiddenListener getHiddenListener() {
		return mHiddenListener;
	}

	public void setHiddenListener(IFooterMenuHiddenListener mHiddenListener) {
		this.mHiddenListener = mHiddenListener;
	}
	
	public boolean canBack(){
		mWebView = mWebViewContainer.peek() ;
		return mWebView.canGoBack();
	}
	
	public void back(){
		mWebView.goBack() ;
	}
	

	private void checkNeedUpdateDialog(
			final WebPluginVerification pluginVerification,
			final UpdateManifestBean pUpdateManifestBean) {
		if (canContinue())
        {
			AlertDialog.Builder _UpdateBuilder = new AlertDialog.Builder(mActivity);
			_UpdateBuilder.setTitle(getDialogTitle()) ;
			String _UpdateMsg = "插件有更新，是否更新？" ;
			if(pUpdateManifestBean!=null&&pUpdateManifestBean.updateDescribe!=null){
				_UpdateMsg = pUpdateManifestBean.updateDescribe ;
			}
			
			_UpdateBuilder.setMessage(_UpdateMsg) ;
			_UpdateBuilder.setPositiveButton("立即更新", new DialogInterface.OnClickListener()
            {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss() ;
					pluginVerification.executeUpdate(pUpdateManifestBean.updateURL,FcpFundTradingFragment.this) ;
				}
              
            });
			_UpdateBuilder.setNegativeButton("暂不更新", new DialogInterface.OnClickListener()
            {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
		            quitSdk();
				}
              
            });
			_UpdateBuilder.setCancelable(true);
			_UpdateBuilder.setOnCancelListener(new DialogInterface.OnCancelListener()
            {
				@Override
				public void onCancel(DialogInterface dialog) {
					dialog.dismiss();
		            quitSdk();							
				}
				 
            }); 
        }
	}
}
